<?php
namespace app\adminjcb\controller;

use app\adminjcb\model\Product as ArticleModel;
use app\common\controller\AdminBaseController;

/**
 * 商品
 */
class ProductController extends AdminBaseController {
    protected $article_model;

    protected function _initialize() {
        parent::_initialize();
        $this->article_model  = new ArticleModel();
    }

    /**
     * 文章管理
     * @param int    $cid 分类ID
     * @param string $keyword 关键词
     * @param int    $page
     * @return mixed
     */
    public function index() {
        $article_list  = db('product')->where("status",1)->select();
        return $this->fetch('index', ['article_list' => $article_list]);
    }

    /**
     * 添加
     * @return mixed
     */
    public function add() {
        return $this->fetch();
    }

    /**
     * 保存
     */
    public function save() {
        if ($this->request->isPost()) {
        	 $data            = $this->request->post();
			$data['add_time']=now_time();
			$data['thumb']=input("thumb_img");
			if ($this->article_model->allowField(true)->save($data)) {
                    $this->success('保存成功',url('product/index'));
            } else {
                    $this->error('保存失败');
            }
            
        }
    }

    /**
     * 编辑
     * @param $id
     * @return mixed
     */
    public function edit($id) {
        $article = db("product")->find($id);
		if ($this->request->isPost()) {
			$data            = $this->request->post();
			$data['add_time']=now_time();
			if(input("thumb_img")){
				$data['thumb']=input("thumb_img");
			}
			if ($this->article_model->allowField(true)->save($data, $id)) {
                    $this->success('保存成功',url('product/index'));
            } else {
                    $this->error('保存失败');
            }
		}
        return $this->fetch('edit', ['article' => $article]);
    }

    /**
     * 更新
     * @param $id
     */
    public function update($id) {
        if ($this->request->isPost()) {
        	$data['title'] = input('title');
			$data['url'] = input('url');
			if (input('thumb_img')) {
				$data['thumb'] = input('thumb_img');
			}
            if (db('ad')->where('id',$id)->update($data) !== false) {
                $this->success('更新成功');
            } else {
                $this->error('更新失败');
            }
        }
    }

    /**
     * 删除
     * @param int   $id
     * @param array $ids
     */
    public function delete($id = 0) {
        $res=db('product')->where("id",$id)->update(['status'=>2]);
        if ($res) {
            $this->success('操作成功',url('product/index'));
        } else {
            $this->error('删除失败');
        }
        
    }

}
